import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/src/entities/format/service_and_product_entity.dart';
import 'package:finance_app/src/router_gen/router_gen_providers.dart';

mixin FormProductsOrServicesMixin<T> on BaseProvider<T> {
  List<ServiceAndProductEntity> serviceAndProductList = [];

  bool usePurchasePrice = false;

  double get subTotal {
    double total = 0.0;
    serviceAndProductList.forEach((element) {
      total += double.parse(element.discountedAmount.toString(), (e) => 0.0);
    });
    return total;
  }

  double get discount => 0.0;

  double get creditUsed => 0.0;

  double get totalDiscount {
    return ((total ?? 0.0) - (creditUsed ?? 0.0) - (discount ?? 0.0))
        .clamp(0.0, double.infinity);
  }

  double get total {
    return subTotal + gst;
  }

  double get gst {
    double total = 0.0;
    serviceAndProductList.forEach((element) {
      if (element.isInclusive == false) {
        total += double.parse(element.discountedAmount.toString(), (e) => 0.0) *
            element.rate /
            100;
      }
    });
    return total;
  }

  double get includesGST {
    double total = 0.0;
    serviceAndProductList.forEach((element) {
      if (element.isInclusive) {
        total += calInclusiveGST(element.discountedAmount, element.rate / 100);
      }
    });
    return total;
  }

  double calInclusiveGST(num amount, num gstRate) {
    if (amount == 0) return 0.0;
    num inclusiveGST = amount - (amount / (1 + gstRate ?? 0)).toDouble();
    return num.parse(inclusiveGST.toStringAsFixed(2));
  }

  void unFocus();

  void onAddItem() async {
    unFocus();
    final result = await Routes.navigateTo(
        RouterGenProviders.productsAndServicesPage,
        params: {
          'isSelectMode': true,
          'isShowZero': true,
          'usePurchasePrice': usePurchasePrice,
        });
    if (result != null) {
      serviceAndProductList.add(result['data']);
      update();
    }
  }

  void onSelectItem(ServiceAndProductEntity value) async {
    final result =
        await Routes.navigateTo(RouterGenProviders.quantityPage, params: {
      'product': value.product,
      'service': value.services,
      'initialNumber': value.number,
    });
    if (result != null) {
      bool delete = result['delete'];
      if (delete == true) {
        serviceAndProductList.remove(value);
      } else {
        if (value.product != null) {
          value.product.fromJson(result['data'].product.toJson());
        }
        if (value.services != null) {
          value.services.fromJson(result['data'].services.toJson());
        }
        value.number = result['data'].number;
      }
      update();
    }
  }
}
